package com.jsmile.cloud.goodscenter.spu.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.jsmile.cloud.goodscenter.api.enums.GoodsCodeEnum;
import com.jsmile.cloud.goodscenter.api.enums.SpuTypeEnum;
import com.jsmile.cloud.goodscenter.api.req.spu.ReqSkuCheck;
import com.jsmile.cloud.goodscenter.api.res.ResSku;
import com.jsmile.cloud.goodscenter.spu.model.ShopSpu;
import com.jsmile.cloud.goodscenter.spu.model.SkuInfo;
import com.jsmile.cloud.goodscenter.spu.model.Spu;
import com.jsmile.cloud.goodscenter.spu.repo.ShopSpuSearchRepository;
import com.jsmile.cloud.goodscenter.spu.repo.SkuInfoSearchRepository;
import com.jsmile.cloud.goodscenter.spu.repo.SpuSearchRepository;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class SkuApplicationService {

    private final SkuInfoSearchRepository skuInfoSearchRepository;
    private final SpuSearchRepository spuSearchRepository;
    private final ShopSpuSearchRepository shopSpuSearchRepository;

    public List<ResSku> skuCheck(ReqSkuCheck reqSkuCheck) {
        log.info("商品库存检查:{]", reqSkuCheck);
        return reqSkuCheck.getSkuList().stream().map(x -> {
            SkuInfo skuInfo = skuInfoSearchRepository.findBySkuIdAndTenantIdAndNumber(x.getSkuId(), reqSkuCheck.getCurTenantId(), x.getSkuNumber(), reqSkuCheck.getHasCheck());
            Spu spu = spuSearchRepository.getSimpleSpu(x.getSpuId(), reqSkuCheck.getCurTenantId());
            if (reqSkuCheck.hasCheck) {// 购物车详情不检查库存，只有加入购物车和更新购物车才检查
                spu.checkStatus();
            }
            ResSku resSku = BeanUtil.toBean(skuInfo, ResSku.class);
            resSku.setSpuInfo(BeanUtil.toBean(spu, ResSku.SpuInfo.class));
            if (SpuTypeEnum.SHOP.getValue() == spu.getSpuType()) {// 自营商品检查
                ShopSpu shopSpu = shopSpuSearchRepository.getSimpleShopSpu(x.getSpuId(), x.getShopId(), reqSkuCheck.getCurTenantId());
                if (reqSkuCheck.hasCheck) {
                    ExceptionKit.checkNotNull(shopSpu, GoodsCodeEnum.SPU_NOT_EXISTS.getResCode(), GoodsCodeEnum.SPU_NOT_EXISTS.getResMsg());
                    shopSpu.checkStatus();
                }
                resSku.getSpuInfo().setShopSaleStatus(shopSpu.getSaleStatus());
            }
            return resSku;
        }).collect(Collectors.toList());
    }

}
